<template>
  <view class="container">
    <!-- 顶部Logo和标题 -->
    <view class="header">
      <image class="logo" src="../static/images/智慧学习.png" mode="aspectFit"></image>
      <text class="title">智慧学习平台</text>
    </view>

    <!-- 登录卡片 -->
    <view class="card">
      <!-- 顶部标签切换 -->
      <!-- <view class="tab-bar">
        <text :class="['tab-item', activeTab === 'login' ? 'active' : '']" @tap="switchTab('login')">登录</text>
        <text :class="['tab-item', activeTab === 'register' ? 'active' : '']" @tap="switchTab('register')">注册</text>
      </view> -->

      <!-- 登录表单 -->
      <view class="form-wrapper" v-if="activeTab === 'login'">
        <!-- 登录方式选择 -->
        <view class="login-type-tabs">
          <text :class="['login-type', loginType === 'password' ? 'active' : '']" @tap="switchLoginType('password')">
            <image class="login-type-icon" src="../static/images/密码登录.png"></image> 密码登录
          </text>
          <text :class="['login-type', loginType === 'phone' ? 'active' : '']" @tap="switchLoginType('phone')">
            <image class="login-type-icon" src="../static/images/手机号登录.png"></image> 手机登录
          </text>
          <!-- <text :class="['login-type', loginType === 'face' ? 'active' : '']" @tap="switchLoginType('face')">
            <text class="iconfont icon-user"></text> 人脸登录
          </text> -->
        </view>

        <!-- 密码登录 -->
        <view v-if="loginType === 'password'" class="form">
          <view class="input-item">
            <image class="input-icon" src="../static/images/密码登录.png"></image>
            <input type="text" placeholder="用户名" v-model="username" />
          </view>
          <view class="input-item">
            <image class="input-icon" src="../static/images/密码.png"></image>
            <input type="password" placeholder="密码" v-model="password" />
          </view>
          <view class="input-item captcha">
            <image class="input-icon" src="../static/images/验证码.png"></image>
            <input type="text" placeholder="验证码" v-model="captchaCode" />
            <image class="captcha-image" v-if="captchaImageUrl" :src="captchaImageUrl" @tap="refreshCaptcha" mode="aspectFit"></image>
          </view>
          <button class="btn-submit" @tap="handlePasswordLogin">登录</button>
        </view>

        <!-- 手机号登录 -->
        <view v-if="loginType === 'phone'" class="form">
          <view class="input-item">
            <image class="input-icon" src="../static/images/手机号.png"></image>
            <input type="text" placeholder="手机号" maxlength="11" v-model="phone" />
          </view>
          <view class="input-item captcha">
            <image class="input-icon" src="../static/images/短信验证码.png"></image>
            <input type="text" placeholder="验证码" maxlength="6" v-model="smsCode" />
            <view class="sms-button" :class="{ disabled: isSmsCounting }" @tap="!isSmsCounting && sendSmsForLogin()">
              {{ isSmsCounting ? `${smsCountdown}s后重新获取` : '获取验证码' }}
            </view>
          </view>
          <button class="btn-submit" @tap="handlePhoneLogin">登录</button>
        </view>

        <!-- 人脸登录 -->
        <view v-if="loginType === 'face'" class="form">
          <view class="face-login-hint">
            <text class="iconfont icon-user face-icon"></text>
            <text class="hint-text">点击下方按钮开启相机进行人脸识别登录</text>
          </view>
          <button class="btn-submit" @tap="openFaceCamera">开启人脸识别</button>
        </view>
      </view>

      <!-- 注册表单 -->
      <view class="form-wrapper" v-if="activeTab === 'register'">
        <view class="form">
          <view class="input-item">
            <text class="iconfont icon-user"></text>
            <input type="text" placeholder="用户名" v-model="registerForm.username" />
          </view>
          <view class="input-item">
            <text class="iconfont icon-lock"></text>
            <input type="password" placeholder="密码(至少6位)" v-model="registerForm.password" />
          </view>
          <view class="input-item">
            <text class="iconfont icon-phone"></text>
            <input type="text" placeholder="手机号" maxlength="11" v-model="registerForm.phone" />
          </view>
          <view class="input-item captcha">
            <text class="iconfont icon-message"></text>
            <input type="text" placeholder="验证码" maxlength="6" v-model="registerForm.smsCode" />
            <view class="sms-button" :class="{ disabled: isRegSmsCounting }" @tap="!isRegSmsCounting && sendRegisterSmsCode()">
              {{ isRegSmsCounting ? `${regSmsCountdown}s后重新获取` : '获取验证码' }}
            </view>
          </view>
          <button class="btn-submit" @tap="handleRegister">注册</button>
        </view>
      </view>

      <!-- 状态消息 -->
      <view class="status-message" v-if="statusMessage">{{ statusMessage }}</view>
    </view>

    <!-- 底部信息 -->
    <view class="footer">
      <text class="footer-text">© 2023 智慧学习平台 All Rights Reserved</text>
    </view>

    <!-- 认证弹窗 -->
    <uni-popup ref="authPopup" type="center">
      <view class="popup-content">
        <view class="popup-title">身份认证</view>
        <view class="popup-form">
          <view class="input-item">
            <text class="iconfont icon-user"></text>
            <input type="text" placeholder="您的姓名" v-model="registerForm.name" />
          </view>
          <view class="input-item">
            <text class="iconfont icon-key"></text>
            <input type="text" placeholder="认证码" v-model="registerForm.authCode" />
          </view>
          <view class="popup-btns">
            <button class="btn-cancel" @tap="closeAuthPopup">取消</button>
            <button class="btn-confirm" @tap="completeRegistration">确认</button>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 人脸识别弹窗 -->
    <uni-popup ref="facePopup" type="center">
      <view class="face-popup">
        <view class="face-popup-title">人脸识别登录</view>
        <view class="face-camera-container">
          <camera v-if="!capturedImage" device-position="front" @error="cameraError" class="face-camera"></camera>
          <image v-else :src="capturedImage" mode="aspectFit" class="captured-face"></image>
        </view>
        <view class="face-buttons">
          <button v-if="!capturedImage" @click="takeFacePhoto" type="primary">拍照</button>
          <block v-else>
            <button @click="resetFacePhoto" type="default">重拍</button>
            <button @click="loginWithFace" type="primary">确认登录</button>
          </block>
          <button @click="closeFacePopup" type="default">取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<style>
page {
  background-color: #f5f5f5;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 30rpx;
  box-sizing: border-box;
}

/* 顶部Logo和标题 */
.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  border-radius: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-top: 20rpx;
  color: #333;
}

/* 卡片样式 */
.card {
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  padding: 30rpx;
  margin: 20rpx 0;
  flex: 1;
}

/* 标签切换 */
.tab-bar {
  display: flex;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 40rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  padding: 20rpx 0;
  color: #666;
}

.tab-item.active {
  color: #4a6bff;
  font-weight: bold;
  position: relative;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 6rpx;
  background-color: #4a6bff;
  border-radius: 3rpx;
}

/* 登录方式选择 */
.login-type-tabs {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40rpx;
}

.login-type {
  font-size: 28rpx;
  color: #666;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
}

.login-type.active {
  background-color: #f0f2ff;
  color: #4a6bff;
}

/* 登录方式图标 */
.login-type-icon {
  width: 20px;
  height: 20px;
  vertical-align: middle;
  margin-right: 5px;
}

/* 表单样式 */
.form {
  display: flex;
  flex-direction: column;
}

.input-item {
  display: flex;
  align-items: center;
  height: 90rpx;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 30rpx;
}

.input-item .iconfont {
  font-size: 40rpx;
  color: #bbb;
  margin-right: 20rpx;
}

.input-item input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
}

/* 验证码样式 */
.captcha {
  position: relative;
}

.captcha-image {
  width: 180rpx;
  height: 70rpx;
  border-radius: 6rpx;
  margin-left: 20rpx;
}

.sms-button {
  background-color: #4a6bff;
  color: white;
  font-size: 24rpx;
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
  white-space: nowrap;
}

.sms-button.disabled {
  background-color: #ccc;
}

/* 提交按钮 */
.btn-submit {
  background-color: #4a6bff;
  color: white;
  border-radius: 45rpx;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  margin-top: 40rpx;
  border: none;
}

/* 人脸登录提示 */
.face-login-hint {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 40rpx 0;
}

.face-icon {
  font-size: 100rpx;
  color: #4a6bff;
  margin-bottom: 20rpx;
}

.hint-text {
  font-size: 28rpx;
  color: #999;
  text-align: center;
  line-height: 1.5;
}

/* 状态消息 */
.status-message {
  background-color: #f0f2ff;
  border: 1rpx solid #d0d6ff;
  color: #4a6bff;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 26rpx;
  text-align: center;
  margin-top: 30rpx;
}

/* 底部信息 */
.footer {
  padding: 30rpx 0;
  text-align: center;
}

.footer-text {
  font-size: 24rpx;
  color: #999;
}

/* 弹窗样式 */
.popup-content {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  width: 600rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.popup-form .input-item {
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 0 20rpx;
  margin-bottom: 20rpx;
}

.popup-btns {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
}

.btn-cancel {
  flex: 1;
  margin-right: 10rpx;
  background-color: #f5f5f5;
  color: #666;
  border: none;
}

.btn-confirm {
  flex: 1;
  margin-left: 10rpx;
  background-color: #4a6bff;
  color: white;
  border: none;
}

.btn-capture {
  flex: 1;
  background-color: #4a6bff;
  color: white;
  border: none;
}

/* 人脸识别相机 */
.face-popup {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  width: 80vw;
}

.face-popup-title {
  text-align: center;
  font-size: 18px;
  margin-bottom: 15px;
}

.face-camera-container {
  width: 100%;
  height: 300px;
  margin-bottom: 15px;
}

.face-camera, .captured-face {
  width: 100%;
  height: 100%;
}

.face-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.face-buttons button {
  flex: 1;
  margin: 0;
  font-size: 14px;
}

.input-icon {
  width: 24px;
  height: 24px;
  margin-right: 20rpx;
}
</style>

<script>
export default {
  data() {
    return {
      // 当前活动标签（登录/注册）
      activeTab: 'login',
      
      // 当前登录类型
      loginType: 'password',
      
      // 账号密码登录
      username: '',
      password: '',
      captchaCode: '',
      captchaKey: '',
      captchaImageUrl: '',
      
      // 手机号登录
      phone: '',
      smsCode: '',
      isSmsCounting: false,
      smsCountdown: 60,
      smsCountdownTimer: null,
      
      // 注册表单
      registerForm: {
        username: '',
        password: '',
        phone: '',
        smsCode: '',
        name: '',
        authCode: ''
      },
      
      // 短信验证码倒计时
      isRegSmsCounting: false,
      regSmsCountdown: 60,
      regSmsCountdownTimer: null,
      
      // 登录状态消息
      statusMessage: '',

      // 人脸识别
      capturedImage: null,
      isProcessing: false
    };
  },
  onLoad() {
    // 组件加载时获取验证码
    this.refreshCaptcha();
  },
  methods: {
    // 切换标签（登录/注册）
    switchTab(tab) {
      this.activeTab = tab;
      if (tab === 'login' && this.loginType === 'password') {
        this.refreshCaptcha();
      }
    },
    
    // 切换登录方式
    switchLoginType(type) {
      this.loginType = type;
      if (type === 'password') {
        this.refreshCaptcha();
      }
    },
    
    // 获取图形验证码
    refreshCaptcha() {
      uni.request({
        url: 'http://localhost:8080/api/captcha',
        method: 'GET',
        success: (res) => {
          if (res.data.status === 10004) {
            const captchaData = res.data.data;
            this.captchaKey = captchaData.captchaKey;
            this.captchaImageUrl = captchaData.captchaImage;
          } else {
            console.error('获取验证码失败:', res.data.message);
          }
        },
        fail: (err) => {
          console.error('获取验证码请求失败:', err);
        }
      });
    },
    
    // 密码登录处理
    handlePasswordLogin() {
      // 验证输入
      if (!this.username || !this.password || !this.captchaCode) {
        this.statusMessage = '请填写完整的登录信息';
        return;
      }

      const loginData = {
        username: this.username,
        password: this.password,
        captchaCode: this.captchaCode,
        captchaKey: this.captchaKey
      };
      
      // 清空之前的状态消息
      this.statusMessage = '正在登录中...';
      
      uni.request({
        url: 'http://localhost:8080/api/login',
        method: 'POST',
        data: loginData,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          console.log('登录响应:', res.data);
          
          if (res.data.status === 10001) {
            const loginResp = res.data.data;
            this.statusMessage = '您已成功登录，正在跳转...';
            
            // 保存登录信息
            this.saveUserInfo({
              token: loginResp.saTokenInfo.tokenValue,
              username: loginResp.username,
              userId: loginResp.userId,
              name: loginResp.name,
              role: loginResp.role
            });
            
            // 根据角色判断跳转
            if (loginResp.role === 2 || loginResp.role === 3) {
              uni.showModal({
                title: '提示',
                content: '教师端/管理员端正在开发中...',
                showCancel: false,
                success: () => {
                  // 清除登录信息
                  uni.clearStorageSync();
                  // 重新获取验证码
                  this.refreshCaptcha();
                  this.statusMessage = '';
                }
              });
            } else if (loginResp.role === 1) {
              this.statusMessage = '您已成功登录，正在跳转...';
              // 延迟后跳转
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/student'
                });
              }, 1500);
            }
          } else {
            this.statusMessage = res.data.message || '登录失败，请重试';
            this.refreshCaptcha();
          }
        },
        fail: (err) => {
          this.statusMessage = '登录失败，请检查网络或联系管理员';
          this.refreshCaptcha();
          console.error(err);
        }
      });
    },
    
    // 手机号登录处理
    handlePhoneLogin() {
      if (!this.phone || !this.smsCode) {
        this.statusMessage = '请输入手机号和验证码';
        return;
      }
      
      const loginData = {
        phone: this.phone,
        smsCode: this.smsCode
      };
      
      this.statusMessage = '正在登录中...';
      
      uni.request({
        url: 'http://localhost:8080/api/login-by-phone',
        method: 'POST',
        data: loginData,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.data.status === 10001) {
            const loginResp = res.data.data;
            this.statusMessage = '您已成功登录，正在跳转...';

            // 保存登录信息
            this.saveUserInfo({
              token: loginResp.saTokenInfo.tokenValue,
              username: loginResp.username,
              userId: loginResp.userId,
              name: loginResp.name,
              role: loginResp.role
            });
            
            // 根据角色判断跳转
            if (loginResp.role === 2 || loginResp.role === 3) {
              uni.showModal({
                title: '提示',
                content: '教师端/管理员端正在开发中，请登录学生账号',
                showCancel: false,
                success: () => {
                  // 清除登录信息
                  uni.clearStorageSync();
                  // 重新获取验证码
                  this.refreshCaptcha();
                  this.statusMessage = '';
                }
              });
            } else if (loginResp.role === 1) {
              this.statusMessage = '您已成功登录，正在跳转...';
              // 延迟后跳转
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/student'
                });
              }, 1500);
            }
          } else {
            this.statusMessage = res.data.message || '登录失败，请重试';
          }
        },
        fail: (err) => {
          this.statusMessage = '登录失败，请检查网络或联系管理员';
          console.error(err);
        }
      });
    },
    
    // 发送登录用短信验证码
    sendSmsForLogin() {
      if (!this.phone || !/^1[3-9]\d{9}$/.test(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        });
        return;
      }

      // 检查手机号是否存在
      uni.request({
        url: `http://localhost:8080/api/check-phone?phone=${this.phone}`,
        method: 'GET',
        success: (res) => {
          if (!res.data.data || !res.data.data.exists) {
            uni.showToast({
              title: '该手机号未注册',
              icon: 'none'
            });
            return;
          }
          
          // 发送短信
          uni.request({
            url: `http://localhost:8080/api/send-sms?phone=${this.phone}`,
            method: 'POST',
            success: (sendRes) => {
              if (sendRes.data.status === 10005) {
                uni.showToast({
                  title: '短信验证码已发送',
                  icon: 'success'
                });
                this.startSmsCountdown();
              } else {
                uni.showToast({
                  title: sendRes.data.message || '短信验证码发送失败',
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              console.error('短信验证码发送请求异常:', err);
              uni.showToast({
                title: '短信验证码发送失败: 网络错误',
                icon: 'none'
              });
            }
          });
        },
        fail: (err) => {
          console.error('检查手机号失败:', err);
          uni.showToast({
            title: '检查手机号失败，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 登录短信验证码倒计时
    startSmsCountdown() {
      this.isSmsCounting = true;
      this.smsCountdown = 60;
      this.smsCountdownTimer = setInterval(() => {
        this.smsCountdown--;
        if (this.smsCountdown <= 0) {
          this.isSmsCounting = false;
          clearInterval(this.smsCountdownTimer);
        }
      }, 1000);
    },
    
    // 发送注册用短信验证码
    sendRegisterSmsCode() {
      // 验证手机号格式
      if (!this.registerForm.phone || !/^1[3-9]\d{9}$/.test(this.registerForm.phone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        });
        return;
      }
      
      // 检查手机号是否已被注册
      uni.request({
        url: `http://localhost:8080/api/check-phone?phone=${this.registerForm.phone}`,
        method: 'GET',
        success: (res) => {
          if (res.data.data && res.data.data.exists) {
            uni.showToast({
              title: '该手机号已被注册',
              icon: 'none'
            });
            return;
          }
          
          // 直接开始倒计时
          this.startRegSmsCountdown();
          
          // 发送短信验证码
          uni.request({
            url: `http://localhost:8080/api/send-sms?phone=${this.registerForm.phone}`,
            method: 'POST',
            success: (sendRes) => {
              if (sendRes.data.status === 0 || sendRes.data.status === 10005) {
                // 添加一个额外提示，应对可能收不到短信的情况
                setTimeout(() => {
                  if (this.registerForm.smsCode === '' && this.activeTab === 'register') {
                    uni.showToast({
                      title: '如果长时间未收到短信，请联系管理员获取验证码',
                      icon: 'none',
                      duration: 3000
                    });
                  }
                }, 30000);
              } else {
                let errorMsg = sendRes.data.message || '短信验证码发送失败';
                uni.showToast({
                  title: `验证码发送失败: ${errorMsg}`,
                  icon: 'none'
                });
                // 发送失败时停止倒计时
                this.stopRegSmsCountdown();
              }
            },
            fail: (err) => {
              let errorMsg = '网络错误';
              uni.showToast({
                title: `短信验证码发送失败: ${errorMsg}`,
                icon: 'none'
              });
              // 发送失败时停止倒计时
              this.stopRegSmsCountdown();
            }
          });
        },
        fail: (err) => {
          console.error('检查手机号失败:', err);
          uni.showToast({
            title: '检查手机号失败，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 开始注册短信倒计时
    startRegSmsCountdown() {
      this.isRegSmsCounting = true;
      this.regSmsCountdown = 60;
      this.regSmsCountdownTimer = setInterval(() => {
        this.regSmsCountdown--;
        if (this.regSmsCountdown <= 0) {
          this.stopRegSmsCountdown();
        }
      }, 1000);
    },
    
    // 停止倒计时
    stopRegSmsCountdown() {
      this.isRegSmsCounting = false;
      clearInterval(this.regSmsCountdownTimer);
    },
    
    // 处理注册表单提交
    handleRegister() {
      // 数据验证
      if (!this.registerForm.username) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        });
        return;
      }
      
      if (!this.registerForm.password || this.registerForm.password.length < 6) {
        uni.showToast({
          title: '密码长度不能少于6位',
          icon: 'none'
        });
        return;
      }
      
      if (!this.registerForm.phone || !/^1[3-9]\d{9}$/.test(this.registerForm.phone)) {
        uni.showToast({
          title: '请输入正确的手机号码',
          icon: 'none'
        });
        return;
      }
      
      if (!this.registerForm.smsCode) {
        uni.showToast({
          title: '请输入短信验证码',
          icon: 'none'
        });
        return;
      }
      
      // 检查用户名是否已存在
      uni.request({
        url: `http://localhost:8080/api/check-username?username=${this.registerForm.username}`,
        method: 'GET',
        success: (res) => {
          if (res.data.data.exists) {
            uni.showToast({
              title: '用户名已存在',
              icon: 'none'
            });
            return;
          }
          
          // 显示认证弹窗
          this.$refs.authPopup.open();
        },
        fail: (err) => {
          console.error('检查用户名失败:', err);
          uni.showToast({
            title: '检查用户名失败，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 关闭认证弹窗
    closeAuthPopup() {
      this.$refs.authPopup.close();
    },
    
    // 完成注册
    completeRegistration() {
      if (!this.registerForm.name) {
        uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        });
        return;
      }
      
      if (!this.registerForm.authCode) {
        uni.showToast({
          title: '请输入认证码',
          icon: 'none'
        });
        return;
      }
      
      // 发送注册请求
      uni.request({
        url: 'http://localhost:8080/api/register',
        method: 'POST',
        data: this.registerForm,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.data.status === 10000) {
            uni.showToast({
              title: '注册成功，请登录',
              icon: 'success'
            });
            this.closeAuthPopup();
            this.resetRegisterForm();
            
            // 切换到登录页
            this.switchTab('login');
          } else {
            uni.showToast({
              title: '注册失败：' + res.data.message,
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('注册失败:', err);
          uni.showToast({
            title: '注册失败，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 重置注册表单
    resetRegisterForm() {
      this.registerForm = {
        username: '',
        password: '',
        phone: '',
        smsCode: '',
        name: '',
        authCode: ''
      };
      if (this.$refs.authPopup) {
        this.$refs.authPopup.close();
      }
    },
    
    // 保存用户信息
    saveUserInfo(userInfo) {
      try {
        // 使用正确的key保存数据
        uni.setStorageSync('satoken', userInfo.token);  // 修改这里，使用 satoken 作为 key
        uni.setStorageSync('userid', userInfo.userId);  // 修改这里，使用 userid 作为 key
        uni.setStorageSync('username', userInfo.username);
        uni.setStorageSync('name', userInfo.name);
        uni.setStorageSync('role', userInfo.role);
        
        // 保存完整对象
        uni.setStorageSync('userInfo', JSON.stringify(userInfo));
        
        console.log('保存的登录信息:', {
          satoken: userInfo.token,
          userid: userInfo.userId,
          username: userInfo.username,
          name: userInfo.name,
          role: userInfo.role
        });
      } catch (e) {
        console.error('保存用户信息失败', e);
        uni.showToast({
          title: '保存登录信息失败',
          icon: 'none'
        });
      }
    },
    
    // 打开人脸识别
    openFaceCamera() {
      this.$refs.facePopup.open();
    },
    
    // 摄像头错误处理
    cameraError(e) {
      console.error('相机错误:', e);
      uni.showToast({
        title: '相机启动失败，请检查权限',
        icon: 'none'
      });
    },
    
    // 拍照
    takeFacePhoto() {
      const ctx = uni.createCameraContext();
      ctx.takePhoto({
        quality: 'normal',
        success: (res) => {
          this.capturedImage = res.tempImagePath;
          console.log('图像已保存:', this.capturedImage);
        },
        fail: (err) => {
          console.error('拍照失败:', err);
          uni.showToast({
            title: '拍照失败，请重试',
            icon: 'none'
          });
        }
      });
    },
    
    // 重新拍照
    resetFacePhoto() {
      this.capturedImage = null;
    },
    
    // 关闭相机
    closeFacePopup() {
      this.capturedImage = null;
      this.$refs.facePopup.close();
    },
    
    // 人脸登录
    loginWithFace() {
      if (!this.capturedImage) {
        uni.showToast({
          title: '请先拍照',
          icon: 'none'
        });
        return;
      }
      
      this.isProcessing = true;
      this.statusMessage = '正在进行人脸识别...';
      
      // 将图片转换为base64
      uni.getFileSystemManager().readFile({
        filePath: this.capturedImage,
        encoding: 'base64',
        success: (res) => {
          const base64 = 'data:image/jpeg;base64,' + res.data;
          
          const requestData = {
            image: base64,
            userId: null
          };
          
          uni.request({
            url: 'http://localhost:8080/api/face/login',
            method: 'POST',
            data: requestData,
            header: {
              'Content-Type': 'application/json'
            },
            success: (res) => {
              console.log('人脸登录响应:', res.data);
              
              if (res.data.status === 10001) {
                const loginResp = res.data.data;
                this.saveUserInfo({
                  token: loginResp.saTokenInfo.tokenValue,
                  username: loginResp.userInfo.username,
                  userId: loginResp.userInfo.userId,
                  name: loginResp.userInfo.name,
                  role: loginResp.userInfo.role
                });
                
                this.statusMessage = '人脸登录成功！欢迎回来, ' + loginResp.userInfo.name;
                this.closeFacePopup();
                
                // 根据角色判断跳转
                if (loginResp.role === 2 || loginResp.role === 3) {
                  uni.showModal({
                    title: '提示',
                    content: '教师端/管理员端正在开发中，请登录学生账号',
                    showCancel: false,
                    success: () => {
                      // 清除登录信息
                      uni.clearStorageSync();
                      // 重新获取验证码
                      this.refreshCaptcha();
                      this.statusMessage = '';
                    }
                  });
                } else if (loginResp.role === 1) {
                  this.statusMessage = '您已成功登录，正在跳转...';
                  // 延迟后跳转
                  setTimeout(() => {
                    uni.reLaunch({
                      url: '/pages/student'
                    });
                  }, 1500);
                }
              } else {
                this.statusMessage = res.data.message || '人脸登录失败。';
                this.isProcessing = false;
              }
            },
            fail: (err) => {
              console.error('人脸登录错误:', err);
              this.statusMessage = '请求失败，请检查网络或联系管理员。';
              this.isProcessing = false;
            }
          });
        },
        fail: (err) => {
          console.error('读取图片失败:', err);
          uni.showToast({
            title: '处理图片失败，请重试',
            icon: 'none'
          });
          this.isProcessing = false;
        }
      });
    }
  },
  onUnload() {
    // 组件卸载时清除所有计时器
    if (this.smsCountdownTimer) {
      clearInterval(this.smsCountdownTimer);
    }
    if (this.regSmsCountdownTimer) {
      clearInterval(this.regSmsCountdownTimer);
    }
  }
}
</script> 